package com.netty4.http.xml;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.jibx.runtime.BindingDirectory;
import org.jibx.runtime.IBindingFactory;
import org.jibx.runtime.IMarshallingContext;
import org.jibx.runtime.IUnmarshallingContext;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.Charset;

public abstract class AbstractHttpXmlDecoder<T> extends MessageToMessageDecoder<T> {
    IBindingFactory factory = null;
    StringReader reader = null;
    final  static String  CHARSET_NAME = "UTF-8";
    final static  Charset UTF_8 = Charset.forName(CHARSET_NAME);
    private Class<?> clazz;
    private boolean isPrint;

    protected  AbstractHttpXmlDecoder(Class<?> clazz){
        this(clazz,false);
    }

    protected  AbstractHttpXmlDecoder(Class<?> clazz,boolean isPrint){
        this.clazz = clazz;
        this.isPrint = isPrint;
    }

    protected Object decode0(ChannelHandlerContext ctx,ByteBuf  body)throws  Exception{
        factory = BindingDirectory.getFactory(clazz);
        String content = body.toString(UTF_8);
        if(isPrint){
            System.out.println("the body is:"+content);
        }
        reader = new StringReader(content);
        IUnmarshallingContext unmarshallingContext = factory.createUnmarshallingContext();
        Object result = unmarshallingContext.unmarshalDocument(reader);
        reader.close();
        reader = null;
        return result;
    }

    public void exceptionCaught(ChannelHandlerContext context,Throwable e){
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            reader = null;
        }
    }

}
